<template>
  <div class="order-container">
    <h1>我的订单</h1>
    
    <el-tabs v-model="activeTab">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待接单" name="pending"></el-tab-pane>
      <el-tab-pane label="配送中" name="delivering"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
    </el-tabs>
    
    <div v-if="orders.length === 0" class="empty-orders">
      <i class="el-icon-takeaway-box"></i>
      <p>暂无订单</p>
    </div>
    
    <div v-else class="order-list">
      <el-card v-for="order in filteredOrders" :key="order.id" class="order-card" shadow="hover">
        <div class="order-header">
          <div class="merchant-info">
            <span class="merchant-name">{{ order.merchantName }}</span>
            <el-tag size="mini" type="info">{{ order.merchantPhone }}</el-tag>
          </div>
          <div class="order-status">
            <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
          </div>
        </div>
        
        <div class="order-items">
          <div v-for="(item, index) in parseOrderItems(order.items)" :key="item.id || index" class="order-item">
            <div class="item-info">
              <span class="item-name">{{ item.productName || item.name || '未知商品' }}</span>
              <span class="item-quantity">x{{ item.quantity || 1 }}</span>
            </div>
            <div class="item-price">¥{{ (item.price || 0).toFixed(2) }}</div>
          </div>
          <div v-if="parseOrderItems(order.items).length === 0" class="empty-item">
            <span>暂无商品信息</span>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-time">
            <i class="el-icon-time"></i>
            <span>{{ formatDate(order.createTime) }}</span>
          </div>
          <div class="order-total">
            <span>共{{ getTotalQuantity(order.items) }}件商品，实付：</span>
            <span class="total-price">¥{{ (order.totalAmount || 0).toFixed(2) }}</span>
          </div>
        </div>
        
        <div class="order-actions">
          <el-button size="small" @click="viewOrderDetail(order.id)">查看详情</el-button>
          <el-button 
            v-if="order.status === 1" 
            type="danger" 
            size="small" 
            @click="cancelOrder(order.id)">
            取消订单
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getUserOrders } from '@/api/user';
import { cancelOrder } from '@/api/order';
import { mapState } from 'vuex';

export default {
  name: 'Order',
  data() {
    return {
      activeTab: 'all',
      orders: [],
      loading: false
    }
  },
  computed: {
    ...mapState(['userInfo']),
    filteredOrders() {
      if (this.activeTab === 'all') return this.orders;

      const statusMap = {
        'pending': 1,    // 待接单
        'delivering': 2, // 配送中
        'completed': 3,  // 已完成
        'cancelled': 4   // 已取消
      };

      return this.orders.filter(order => {
        return order.status === statusMap[this.activeTab];
      });
    }
  },
  created() {
    // 加载订单数据
    this.loadOrders();
  },
  methods: {
    loadOrders() {
      if (!this.userInfo || !this.userInfo.id) {
        this.$message.warning('请先登录');
        this.$router.push('/login?redirect=' + this.$route.fullPath);
        return;
      }

      this.loading = true;

      // 调用API获取订单数据
      getUserOrders(this.userInfo.id, {
        page: 1,
        size: 100 // 获取较多订单
      }).then(res => {
        if (res.code === 200) {
          this.orders = res.data.records || [];
        } else {
          this.$message.error(res.message || '获取订单失败');
        }
      }).catch(err => {
        console.error('获取订单失败', err);
        this.$message.error('获取订单失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}`;
    },
    getTotalQuantity(items) {
      try {
        // 处理字符串格式的items
        const itemsArray = this.parseOrderItems(items);
        return itemsArray.reduce((sum, item) => sum + (item.quantity || 0), 0);
      } catch (e) {
        console.error('解析订单商品失败', e);
        return 0;
      }
    },
    parseOrderItems(items) {
      if (!items) return [];
      
      try {
        // 如果是字符串，尝试解析JSON
        if (typeof items === 'string') {
          return JSON.parse(items);
        }
        // 如果已经是数组，直接返回
        if (Array.isArray(items)) {
          return items;
        }
        return [];
      } catch (e) {
        console.error('解析订单商品失败', e);
        return [];
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待接单',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    getStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      };
      return typeMap[status] || '';
    },
    viewOrderDetail(orderId) {
      this.$router.push(`/order/${orderId}`);
    },
    cancelOrder(orderId) {
      this.$confirm('确定要取消该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        // 调用API取消订单
        cancelOrder(orderId)
          .then(res => {
            if (res.code === 200) {
              // 更新本地状态
              const order = this.orders.find(o => o.id === orderId);
              if (order) {
                order.status = 4; // 已取消
              }
              this.$message.success('订单已取消');
            } else {
              this.$message.error(res.message || '取消订单失败');
            }
          })
          .catch(err => {
            console.error('取消订单失败', err);
            this.$message.error('取消订单失败');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {});
    }
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
}
.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}
.empty-orders i {
  font-size: 48px;
  color: #ccc;
}
.empty-orders p {
  color: #999;
  margin-top: 10px;
}
.order-list {
  margin-top: 20px;
}
.order-card {
  margin-bottom: 20px;
}
.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.merchant-name {
  font-weight: bold;
  margin-right: 10px;
}
.order-items {
  padding: 10px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}
.order-item {
  display: flex;
  justify-content: space-between;
  padding: 5px 0;
}
.item-info {
  display: flex;
}
.item-name {
  margin-right: 10px;
}
.item-quantity {
  color: #999;
}
.item-price {
  font-weight: bold;
}
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}
.order-time {
  color: #999;
}
.order-time i {
  margin-right: 5px;
}
.total-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
.order-actions {
  margin-top: 15px;
  text-align: right;
}
</style> 